package cn.com.lyb;


import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;

public class FileScannerDemo {
    public static void main(String[] args) {
        Path dir = Paths.get("D:\\opt\\yeexun"); // 指定目录路径
        LocalDateTime startTime = LocalDateTime.of(2024, 8, 27, 11, 0); // 开始时间
        LocalDateTime endTime = LocalDateTime.of(2024, 8, 27, 23, 59); // 结束时间

        List<Path> newFiles = findNewFiles(dir, startTime, endTime);

        System.out.println("在指定时间区间内新增的文件：");
        newFiles.forEach(System.out::println);
    }

    public static List<Path> findNewFiles(Path dir, LocalDateTime startTime, LocalDateTime endTime) {
        List<Path> newFiles = new ArrayList<>();

        try {
            Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    // 获取文件的创建时间
                    FileTime creationTime = (FileTime) Files.getAttribute(file, "basic:creationTime");
                    LocalDateTime fileCreationTime = creationTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

                    // 检查文件是否在指定时间区间内创建
                    if (fileCreationTime.isAfter(startTime) && fileCreationTime.isBefore(endTime)) {
                        newFiles.add(file);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

        return newFiles;
    }
}
